<?php

namespace App\Http\Controllers\Admin\Manager;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Requests\Admin\StoreRolePostRequest;

use App\Models\Admin\Role;

class RoleController extends Controller
{   
    public $module = 'role_tag';

    public $parent_module = 'rbac';

    public $breadcrumb_name = 'role';

    public $page_name = 'RBAC';

    public $page_describe = '角色管理';

    private $roleArr = [
        'name' => '',
        'display_name' => '',
        'description' => ''
    ];

    public function index()
    {   
        $roles = Role::paginate(25);
        $permissions = \App\Models\Admin\Permission::all();
        return view('manager.role.index', compact('roles', 'permissions'));
    }

    public function create()
    {
        $permissions = \App\Models\Admin\Permission::all();
        return view('manager.role.create', compact('permissions'));
    }

    public function store(StoreRolePostRequest $request)
    {
        try {
            $role = new Role();
            foreach (array_keys($this->roleArr) as $key) {
                $role->$key = $request->get($key);
            }
            $role->save();
            if (is_array($request->get('permissions'))) {
                $role->givePermissionsTo($request->get('permissions'));
            }
            return redirect()->route('role.index')->withSuccess('新增角色成功');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()))->withInput();
        }
        // dd($request->get('permissions'));
    }

    public function show($id)
    {
        dd('不支持预览！');
    }

    public function edit($id)
    {
        $role = Role::find($id);
        $permissions = \App\Models\Admin\Permission::all();
        $perms = [];
        if ($role->perms) {
            foreach ($role->perms as $key) {
                $perms[] = $key->id;
            }
        }
        return view('manager.role.edit', compact('role', 'permissions', 'perms'));
    }

    public function update(StoreRolePostRequest $request, $id)
    {
        try {
            $role = Role::find((int)$id);
            foreach (array_keys($this->roleArr) as $key) {
                $role->$key = $request->get($key);
            }
            $role->save();
            $role->givePermissionsTo($request->get('permissions',[]));
            return redirect()->back()->withSuccess('编辑角色成功');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()))->withInput();
        }
    }

    public function destroy($id)
    {
        try {
            if (Role::whereId($id)->delete()) {
                return redirect()->back()->withSuccess('删除角色成功');
            }
        } catch(\Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()));
        }
    }
}
